<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Storage;
use Exception;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;

class RunGameItems extends Model
{
    public $timestamps = false;
    protected $table = "run_game_items";


    /**
     * 导入题库
     * @param $datas
     * @return array
     */
    static function ItemsAdd($request)
    {
        $time = time();
        $insert = [];
        //获取文件内容
        try {
            $name = $request->items->getClientOriginalName();
            $pri = explode('.', $name);
            if ($pri[1] !== 'xls' && $pri[1] !== 'xlsx') {
                return ['status' => 2, 'message' => '文件类型应为xls或者xlsx！'];
            }
            $file_name = storage_path('app/items/' . $name);
            move_uploaded_file($request->items->path(), $file_name);//将上传到服务器临时文件夹的文件重新移动到新位置

            if ($pri[1] === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($file_name);
            $datas = $spreadsheet->getAllSheets()[0]->toArray();
            if (!count($datas)) {
                return ['status' => 2, 'message' => '检测到题库里面没有题！'];
            }
            //导入题库
            if (count($datas)) {
                foreach ($datas as $data) {
                    if ($data[0]) {
                        $insert[] = [
                            'title' => $data[0],
                            'answer' => intval($data[1]),
                            'created_at' => $time,
                        ];
                    }
                }
            }
            if (!RunGameItems::insert($insert)) {
                return ['status' => 2, 'message' => '失败'];
            }
        } catch (Exception $exception) {
            logger($exception);
            return ['status' => 2, 'message' => '出现异常'];
        }

        Storage::disk('local')->delete('items/' . $name);
        return ['status' => 1, 'message' => '成功'];
    }
}
